from django import template
register = template.Library()

from django.utils.html import format_html


# 自定义标签 计算商品和
@register.simple_tag
def cartsum(n1,n2):
    res = n1 * n2
    return "%.2f"%(res)



# 自定义标签 解决缩进问题
@register.simple_tag
def sj(res):
    num = res.count(',')-1
    res = num * '|____'
    return format_html(res)



# 自定义分页标签
@register.simple_tag

def ShowPages(count,request):
    p = int(request.GET.get('p',1))
    begin = p - 2
    end = p + 3
    # 当选中的页数小于5时
    if p < 3:
        begin = 1
        end = 6
    if p > (count-3):
        begin = count - 5
        end = count

    if count < 6:
        begin = 1
        end = count

    # 获取页面上的其他搜索条件 
    data = request.GET.dict()
    data.pop('p',None)
    res = ''
    
    for k,v in data.items():
        res += '&'+k+'='+v
    ps = ''
    # 上一页
    if p > 1:
        ps += '<li><a href="?p='+ str(p-1) + res +'">«</a></li>'

    # 首页
    ps += '<li><a href="?p=1'+res+'">首页</a></li>'
    for x in range(begin,end + 1):
        # 判断是否为当前页
        if p == x:
            ps += '<li class="am-active"><a href="?p='+ str(x) + res +'">'+ str(x) +'</a></li>'
        else:
            ps += '<li><a href="?p='+ str(x) + res +'">'+ str(x) +'</a></li>'
    # 尾页
    ps += '<li><a href="?p='+ str(count) + res +'">尾页</a></li>'
    # 下一页
    if p < count:
        ps += '<li><a href="?p='+ str(p+1) + res +'">»</a></li>'

    return format_html(ps)